package com.kedacom.ctsp.authz.aspect;

import com.kedacom.ctsp.authz.Authorize;
import com.kedacom.ctsp.authz.entity.AuthContext;
import com.kedacom.ctsp.authz.entity.Authentication;
import com.kedacom.ctsp.authz.exception.UnauthorizedException;
import com.kedacom.ctsp.lang.ClassUtil;
import com.kedacom.ctsp.orm.param.Param;
import com.kedacom.ctsp.web.aop.context.MethodInterceptorContext;
import com.kedacom.ctsp.web.aop.context.MethodInterceptorHolder;
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import org.aopalliance.intercept.MethodInterceptor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Authorize切点
 *
 * @author xuwei
 * @create 2017-11-30 15:28
 **/
public class AopAuthorizeAdvisor extends StaticMethodMatcherPointcutAdvisor {

    public AopAuthorizeAdvisor(AuthorizeService authorizeService) {
        super((MethodInterceptor) methodInvocation -> {
            MethodInterceptorHolder holder = MethodInterceptorHolder.create(methodInvocation);
            MethodInterceptorContext paramContext = holder.createParamContext();

            Authentication authentication = Authentication.current().orElseThrow(UnauthorizedException::new);

            AuthContext context = new AuthContext(authentication, paramContext);

            authorizeService.handle(context);

            Set<String> tempIncludes = new HashSet<>();
            Set<String> tempExcludes = new HashSet<>();

            paramContext.getParameter(Param.class).ifPresent(
                    param -> {
                        tempIncludes.addAll(param.getIncludes());
                        tempExcludes.addAll(param.getExcludes());
                    }
            );

            Object obj = methodInvocation.proceed();
            if (obj != null && obj instanceof ResponseMessage) {
                ResponseMessage responseMessage = (ResponseMessage) obj;
                if (CollectionUtils.isNotEmpty(tempIncludes)) {
                    // 设置可以显示的字段
                    responseMessage.setFields(new LinkedHashSet<>(CollectionUtils.removeAll(tempIncludes, tempExcludes)));
                }else{
                    responseMessage.setFields(new LinkedHashSet<>());
                }
            }
            return obj;
        });
    }

    @Override
    public boolean matches(Method method, Class<?> aClass) {
        //对controller进行控制, 只判断类, 或者父类上是否有Authorize标签.
        return ClassUtil.getAnnotation(aClass, Authorize.class) != null;
    }
}
